package com.springboot.base.springbootes.elasticsearch;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: 船长
 * @create: 2025-02-17 21:17
 **/

@Configuration
public class ElasticSearchConfig {


    // ES服务器ip
    @Value("${elasticsearch.esHost}")
    private String esHost;

    // ES服务器端口
    @Value(("${elasticsearch.esPort}"))
    private Integer esPort;

    // ES服务器协议 http/https
    @Value(("${elasticsearch.esScheme}"))
    private String esScheme;

    // ES 用户名
    @Value("${elasticsearch.username}")
    private String username;

    // ES 密码
    @Value("${elasticsearch.password}")
    private String password;

    @Bean
    public RestHighLevelClient restHighLevelClient(){
//        RestHighLevelClient client = new RestHighLevelClient(
//                RestClient.builder(
//                        new HttpHost(esHost, esPort,esScheme)
//                )
//        );
//        return client;

        // 创建认证提供者
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(
                AuthScope.ANY,
                new UsernamePasswordCredentials(username, password)
        );

        // 创建RestClientBuilder并设置认证
        RestClientBuilder builder = RestClient.builder(
                new HttpHost(esHost, esPort, esScheme)
        ).setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            // 配置连接池
            httpClientBuilder.setMaxConnTotal(100); // 最大连接数
            httpClientBuilder.setMaxConnPerRoute(10); // 每个路由的最大连接数
            return httpClientBuilder;
        });

        // 创建RestHighLevelClient
        return new RestHighLevelClient(builder);
    }
}
